﻿import requests
import itchat
from itchat.content import *
import json
import time
import datetime
import threading

robot_flag = 0
flag_time=''
KEY = 'b31264c901684cd39386fc2c9699c9ba'

def loop():
    hello = {'00': '晚安', '06': '早安', '12': '中午好', '18': '下午好'}
    while True:
        time.sleep(1)
        nowtime=datetime.datetime.now()
        now = str(nowtime)[14:19]
        if now=='00:00':
            if str(nowtime)[11:13] in hello:
                hello_words=hello[str(nowtime)[11:13]]
                users = itchat.search_friends(name='馨儿')
                userName = users[0]
                chatroom = itchat.search_chatrooms(name='宝宝躺下了')[0]
                itchat.send_msg(hello_words, userName['UserName'])
                itchat.send_msg(hello_words, chatroom['UserName'])
                if str(nowtime)[11:13]=='06':
                    replycontent = task('成都今天天气怎么样')
                    itchat.send_msg(replycontent, chatroom['UserName'])
                    itchat.send_msg(replycontent, userName['UserName'])
            else:
                users = itchat.search_friends(name='馨儿')
                userName = users[0]
                replycontent = task('现在几点')
                itchat.send_msg(replycontent, userName['UserName'])
                chatroom=itchat.search_chatrooms(name='宝宝躺下了')[0]
                itchat.send_msg('整点报时', chatroom['UserName'])
t1 = threading.Thread(target=loop, name='LoopThread')
t1.start()

def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return

def task(question):
    return get_response(question)

@itchat.msg_register([TEXT,PICTURE],isGroupChat=True,isFriendChat=True)

def simple_reply(msg):
    global robot_flag,flag_time
    if str(msg['Text'])== '召唤机器人':
        robot_flag=1
        flag_time =str(datetime.datetime.now() + datetime.timedelta(minutes=5))[:-7]
    elif robot_flag==1:
        if str(msg['Text'])== '退出机器人':
            robot_flag = 0
        if str(datetime.datetime.now())[:-7]==flag_time:
            robot_flag = 0
        member_list=['宝宝躺下了','徐香香']
        if msg['User']['NickName'] in member_list:
            reply = get_response(msg['Text'])
            return reply
    elif str(msg['Text'])[0]=='！':
        reply = get_response(msg['Text'])
        return reply

itchat.auto_login(enableCmdQR=2)
itchat.run()

